//
//  QLMPayMoneyVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/11/6.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMPayMoneyVC.h"
#import <WXApiObject.h>
#import <WXApi.h>
#import "QLMQRCodeVC.h"
#import "QLMPaySuccessVC.h"
#import "QLBxOrderCostVC.h"

@interface QLMPayMoneyVC ()<UITableViewDelegate,UITableViewDataSource>{
    UITableViewCell *paycell;
    UIButton *alipayBtn;
    UIButton *wechatBtn;
    UIButton *POSBtn;
    NSString *typeStr;
}
@property (nonatomic,strong) UITableView *paytableview;
@end

@implementation QLMPayMoneyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"支付详情";
    
    CGRect rect=CGRectMake(0, 0, kScreen_width, kScreen_height-IOS11_OR_LATER_SPACE(34)-QLM_StatusBarAndNavigationBarHeight-44);
    _paytableview=[[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    _paytableview.backgroundColor=[UIColor clearColor];
    _paytableview.delegate=self;
    _paytableview.dataSource=self;
    _paytableview.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    _paytableview.showsVerticalScrollIndicator=NO;
    _paytableview.showsHorizontalScrollIndicator=NO;
    _paytableview.tableFooterView=[UIView new];
    [self.view addSubview:_paytableview];
    
    UIButton *saveButton = [[UIButton alloc] init];
    saveButton.frame=CGRectMake(0, kScreen_height-44-IOS11_OR_LATER_SPACE(34)-QLM_StatusBarAndNavigationBarHeight, kScreen_width, 44);
    [saveButton setTitle:@"去支付" forState:UIControlStateNormal];
    saveButton.titleLabel.font=[UIFont systemFontOfSize:18.0f];
    [saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    saveButton.backgroundColor = kButtonColor;
    [saveButton addTarget:self action:@selector(payMoneyAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveButton];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - 支付相关方法
- (void)payMoneyAction:(UIButton *)btn{

//    QLMPaySuccessVC *successVC=[QLMPaySuccessVC new];
//    self.hidesBottomBarWhenPushed=YES;
//    [self.navigationController pushViewController:successVC animated:YES];
    
    if ([typeStr isEqualToString:@"3"]) {
        
        QLMQRCodeVC *codeVC=[QLMQRCodeVC new];
        codeVC.orderId=_orderListInfoModel.erpOrderNo;
        self.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:codeVC animated:YES];
        
    }else{
        [self requestOrderInfoData];
    }
}

- (void)pushToCustomVC{
    for (UIViewController *VC in self.navigationController.viewControllers) {
        if ([VC isKindOfClass:[QLBxOrderCostVC class]]) {
            QLBxOrderCostVC *costVC=(QLBxOrderCostVC *)VC;
            costVC.isBXPayMoneyJumpBool=YES;
            [self.navigationController popToViewController:VC animated:YES];
        }
    }
}

- (void)payAlipay:(NSString *)orderStr{
    [[AlipaySDK defaultService] payOrder:orderStr
                              fromScheme:@"xiaomakuaixiuAlisdk"
                                callback:^(NSDictionary *resultDic){
                                    NSInteger status = [[resultDic objectForKey:@"resultStatus"] integerValue];
                                    if (status == 9000) {
                                        ETToast(@"支付成功");
                                        [self pushToCustomVC];
                                    }else if(status == 8000){
                                        ETToast(@"处理中");
                                    }else if(status == 4000){
                                        ETToast(@"支付失败");
                                    }else if(status == 6001){
                                        ETToast(@"取消支付");
                                    }else if(status == 5000){
                                        ETToast(@"重复请求");
                                    }
                                }];
}

-(void)payWeixin:(NSDictionary *)paramDic{
    if ([WXApi isWXAppInstalled]) {
        [self weixinChooseAct:paramDic];
    }else{
        ETToast(@"未检测到微信客户端，请安装之后再进行支付！");
        return;
    }
}

- (void)requestOrderInfoData{
    if (typeStr.length==0) {
        ETToast(@"请选择支付方式！");
        return;
    }
    
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:typeStr forKey:@"type"];
    [paramerDic setObject:_orderListInfoModel.erpOrderNo forKey:@"orderNo"];
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/pay" withParamers:paramerDic andBody:nil
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            if ([typeStr isEqualToString:@"1"]) {
                                [self payAlipay:responseObject[@"data"]];
                            }else if([typeStr isEqualToString:@"2"]) {
                                [self payWeixin:responseObject[@"data"]];
                            }
 
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

#pragma mark - 微信支付相关方法
- (void)weixinChooseAct:(NSDictionary *)paramDic{
   [self WXPayRequestWithNonceStr:paramDic[@"noncestr"]
                          package:paramDic[@"package"]
                        partnerId:paramDic[@"partnerid"]
                         prepayId:paramDic[@"prepayid"]
                        timeStamp:[paramDic[@"timestamp"] intValue]
                             sign:paramDic[@"sign"]];
}

//调起微信接口
- (void)WXPayRequestWithNonceStr:(NSString *)nonceStr package:(NSString *)package partnerId:(NSString *)partnerId prepayId:(NSString *)prepayId timeStamp:(int)timeStamp sign:(NSString *)sign{
    PayReq* wxreq = [[PayReq alloc] init];
    wxreq.partnerId= partnerId;
    wxreq.prepayId= prepayId;
    wxreq.nonceStr= nonceStr;
    wxreq.timeStamp= timeStamp;
    wxreq.package= package;
    wxreq.sign=sign;
    [WXApi sendReq:wxreq];
}

#pragma mark - UITableView datasource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 100;
    }
    return 34;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView=[[UIView alloc] init];
    headerView.backgroundColor=[UIColor whiteColor];
    if (section==1) {
        UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
        newButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
        newButton.frame = CGRectMake(15, 5, 160, 24);
        [newButton setImage:[UIImage imageNamed:@"icon"] forState:UIControlStateNormal];
        [newButton setTitle:@"请选择支付方式" forState:UIControlStateNormal];
        [newButton setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
        newButton.titleLabel.font=[UIFont systemFontOfSize:18.0f];
        newButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        newButton.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
        [headerView addSubview:newButton];
        
        UIView *lineView=[[UIView alloc] initWithFrame:CGRectMake(0, 33.5, kScreen_width, 0.5)];
        lineView.backgroundColor=[UIColor lightGrayColor];
        [headerView addSubview:lineView];
    }else{
        UILabel *addreTipLabel=[[UILabel alloc] initWithFrame:CGRectMake(20, 20, kScreen_width-20*2,60)];
        addreTipLabel.font=[UIFont systemFontOfSize:30];
        addreTipLabel.textColor=[UIColor redColor];
        
        if (self.moneyStr.length==0) {
            addreTipLabel.text=@"￥0";
        }else{
            addreTipLabel.text=[NSString stringWithFormat:@"￥%@",self.moneyStr];
        }
        addreTipLabel.textAlignment=NSTextAlignmentCenter;
        [headerView addSubview:addreTipLabel];
    }
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==0) {
        return 10;
    }
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView=[[UIView alloc] init];
    footerView.backgroundColor=[UIColor clearColor];
    footerView.userInteractionEnabled=YES;
    return footerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellid=[NSString stringWithFormat:@"cellids%ld",indexPath.row];
    paycell = [tableView cellForRowAtIndexPath:indexPath];
    paycell.selectionStyle=UITableViewCellSelectionStyleNone;
    if (!paycell) {
        paycell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
    }

    if (indexPath.row==2) {
        UIView *lineView=[[UIView alloc] initWithFrame:CGRectMake(0,43.5,kScreen_width,0.5)];
        lineView.backgroundColor=[UIColor lightGrayColor];
        [paycell addSubview:lineView];
    }

    NSString *imageNameStr=@"alipay";
    NSString *titleStr=@"推荐使用支付宝用户使用";
    CGFloat imageWidth=55;
    if (indexPath.row==1) {
        imageNameStr=@"wechat";
        titleStr=@"操作简单易用，支持大额支付";
        imageWidth=80;
    }else if (indexPath.row==2) {
        imageNameStr=@"tonglian_logo";
        titleStr=@"POS机简单易用，支持大额支付";
        imageWidth=80;
    }

    UIImageView *aImageView=[[UIImageView alloc] initWithFrame:CGRectMake(20, 12, imageWidth, 20)];
    aImageView.image=[UIImage imageNamed:imageNameStr];
    [paycell addSubview:aImageView];

    UILabel *addreTipLabel=[[UILabel alloc] initWithFrame:CGRectMake(80+20+10, 7, kScreen_width-80-20-10, 30)];
    addreTipLabel.font=[UIFont systemFontOfSize:16];
    addreTipLabel.textColor=UIColorFromRGB(0x333333);
    addreTipLabel.text=titleStr;
    addreTipLabel.textAlignment=NSTextAlignmentLeft;
    addreTipLabel.backgroundColor=[UIColor clearColor];
    [paycell addSubview:addreTipLabel];
    
    UIButton *selButton = [UIButton buttonWithType:UIButtonTypeCustom];
    selButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
    selButton.frame = CGRectMake(kScreen_width-14-20, 15, 14, 14);
    selButton.tag=660+indexPath.row;
    [selButton setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
    [paycell addSubview:selButton];

    if (indexPath.row==0) {
        alipayBtn=selButton;
    }else if (indexPath.row==1){
        wechatBtn=selButton;
    }else if (indexPath.row==2){
        POSBtn=selButton;
    }
    return paycell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 0;
    }
    return 3;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

#pragma mark - UITableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row==0) {
        typeStr=@"1";
        [alipayBtn setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateNormal];
        [wechatBtn setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
        [POSBtn setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
    }else if (indexPath.row==1){
        typeStr=@"2";
        [alipayBtn setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
        [wechatBtn setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateNormal];
        [POSBtn setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
    }else{
        typeStr=@"3";
        [alipayBtn setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
        [wechatBtn setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
        [POSBtn setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateNormal];
    }
}

@end
